package com.k52group.vn.micromarket.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Patterns;

import com.google.gson.Gson;
import com.k52group.vn.micromarket.classes.Profile;

public class Utils {
	public static String getData(String key, Context context) {
		SharedPreferences settings = context.getSharedPreferences(
				Constant.APP_NAME, Activity.MODE_PRIVATE);
		System.out.println("data get from setting "+settings.getString(key, ""));
		return settings.getString(key, "");
	}

	public static void saveData(String key, String value, Context context) {
		SharedPreferences settings = context.getSharedPreferences(
				Constant.APP_NAME, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);
		editor.commit();
	}

	public static Profile profile(Context context) {
		String data = getData(Constant.USER, context);
		return new Gson().fromJson(data, Profile.class);
	}

	public static String getDeviceID(Context context) {
		TelephonyManager manager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId;
		if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
			// Tablet
			deviceId = Secure.getString(context.getContentResolver(),
					Secure.ANDROID_ID);

		} else {
			// Mobile
			deviceId = manager.getDeviceId();

		}
		return deviceId;
	}

	public static double distance(double lat1, double lat2, double lon1,
			double lon2, double el1, double el2) {

		final int R = 6371; // Radius of the earth

		Double latDistance = deg2rad(lat2 - lat1);
		Double lonDistance = deg2rad(lon2 - lon1);
		Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
				+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
				* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
		Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double distance = R * c * 1000; // convert to meters

		double height = el1 - el2;
		distance = Math.pow(distance, 2) + Math.pow(height, 2);
		return Math.sqrt(distance);
	}

	public static double deg2rad(double deg) {
		return (deg * Math.PI / 180.0);
	}

	public static boolean isEmailValid(CharSequence email) {
		if (email.toString().trim().equals(""))
			return true;
		return !Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}

	public static Location getLocation(Context context) {
		LocationManager lm = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		Location location = lm
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (location == null)
			location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		return location;
	}
}
